package com.rinvay.asdownloader.persistent;

import java.util.ArrayList;

import com.rinvay.network.filedownload.model.DownloadTask;
import com.rinvay.utils.logger.Log;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DownloadTaskDAO
{
    private static final String TAG = "DownloadTaskDAO";

    private static DownloadTaskDAO instance = null;

    private FileDownloadHelper helper = null;

    private DownloadTaskDAO(Context context) {
        helper = FileDownloadHelper
                .getInstance(context.getApplicationContext());
    }

    public static synchronized void createInstance(Context context) {
        if (instance == null) {
            instance = new DownloadTaskDAO(context);
        }
    }

    public static DownloadTaskDAO getInstance() {
        return instance;
    }

    public long insertDownloadTask(DownloadTask task) {
        Log.i(TAG, "insert to db:" + task);
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DownloadTaskData.KEY_UUID, task.getUUId());
        values.put(DownloadTaskData.KEY_URL, task.getResourceUrl());
        values.put(DownloadTaskData.KEY_FILE_NAME, task.getFileName());
        values.put(DownloadTaskData.KEY_DIRECTORY, task.getFileDirectory());
        values.put(DownloadTaskData.KEY_ISFINISHED, "" + false);
        values.put(DownloadTaskData.KEY_SIZE, task.getSize());

        return db.insert(FileDownloadHelper.TABLE_DOWNLOAD_TASK, null, values);
    }

    public synchronized void updateDownloadTask(DownloadTask task) {
        Log.i(TAG, "update db:" + task);
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DownloadTaskData.KEY_ISFINISHED, "" + task.isTaskFinished());
        values.put(DownloadTaskData.KEY_SIZE, task.getSize());
        values.put(DownloadTaskData.KEY_CUR_LENGTH, task.getCurLength());
//        if (!task.isTaskFinished()) {
        values.put(DownloadTaskData.KEY_THREAD_SIZE, task.getThreadSize());
        values.put(DownloadTaskData.KEY_PART_DATA,
                PartDataTool.buildPartsData(task.getParts()));
//        }

        int rows = db.update(FileDownloadHelper.TABLE_DOWNLOAD_TASK, values,
                DownloadTaskData.KEY_UUID + " = ? ", new String[] {
                    task.getUUId() + ""
                });
        Log.i(TAG, rows + "rows affected");
    }

    public void deleteDownloadTask(DownloadTask task) {
        Log.i(TAG, "deleteDownloadTask from db");
        SQLiteDatabase db = helper.getWritableDatabase();
        int rows = db.delete(FileDownloadHelper.TABLE_DOWNLOAD_TASK,
                DownloadTaskData.KEY_UUID + "=?", new String[] {
                    task.getUUId()
                });
        Log.i(TAG, rows + "rows deleted");
    }

    public ArrayList<DownloadTask> queryAllDownloadTask() {
        Log.i(TAG, "queryAllDownloadTask from db");
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cr = db.query(FileDownloadHelper.TABLE_DOWNLOAD_TASK, null,
                null, null, null, null, null);
        ArrayList<DownloadTask> taskes = new ArrayList<DownloadTask>();
        DownloadTask task;
        while (cr.moveToNext()) {

            String uuid = cr.getString(cr
                    .getColumnIndex(DownloadTaskData.KEY_UUID));
            String url = cr.getString(cr
                    .getColumnIndex(DownloadTaskData.KEY_URL));
            String directory = cr.getString(cr
                    .getColumnIndex(DownloadTaskData.KEY_DIRECTORY));
            String name = cr.getString(cr
                    .getColumnIndex(DownloadTaskData.KEY_FILE_NAME));
            int size = cr.getInt(cr.getColumnIndex(DownloadTaskData.KEY_SIZE));
            boolean isfinished = Boolean.parseBoolean(cr.getString(cr
                    .getColumnIndex(DownloadTaskData.KEY_ISFINISHED)));

            task = new DownloadTask(url, directory, name, 0);
            task.setUuid(uuid);
            task.setSize(size);
            task.setTaskFinished(isfinished);
            if (!isfinished) {
                int curlength = cr.getInt(cr
                        .getColumnIndex(DownloadTaskData.KEY_CUR_LENGTH));
                int threadsize = cr.getInt(cr
                        .getColumnIndex(DownloadTaskData.KEY_THREAD_SIZE));
                String partStr = cr.getString(cr
                        .getColumnIndex(DownloadTaskData.KEY_PART_DATA));

                task.setPreLength(curlength);
                task.setThreadSize(threadsize);
                if (partStr != null && !partStr.equals("")) {
                    PartDataTool.parsePartsData(task, partStr);
                    task.setState(DownloadTask.STATE_PAUSED);
                }
            }
            Log.i(TAG, "get task from db:" + task);
            taskes.add(task);
        }
        cr.close();
        return taskes;
    }

}
